package orfeu.engine;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import javax.microedition.khronos.opengles.GL10;

public class Buton extends Sprite {

	public Buton(float w, float h, int nf, long fp, int res)
	{
		// set quad properties
		width = w;
		height = h;
		
		// set sprite properties
		noFrames = nf;
		currentFrame = 0;
		framePeriod = fp;
		resource = res;
		
		// set drawable properties
		px = py = 0;
		rx = ry = 0;
		sx = sy = 1;
		
		// set vertices
		vertices = new float[] {-width, -height, 0.0f,
								width, -height, 0.0f,
								width, height, 0.0f,
								-width, height , 0.0f};
		
		// generate texture coordinates for the first frame
		texcoords = new float[] {(float)currentFrame * 1 / (float)noFrames, 0.0f,
								 (float)(currentFrame + 1) * 1 / (float)noFrames, 0.0f,
								 (float)(currentFrame + 1) * 1 / (float)noFrames, 1.0f,
								 (float)currentFrame * 1 / (float)noFrames, 1.0f};
		
		// build buffer objects
		ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4); // 4 bytes per float
		vbb.order(ByteOrder.nativeOrder());
		vertexBuffer = vbb.asFloatBuffer();
		vertexBuffer.put(vertices);
		vertexBuffer.position(0);

		ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * 2); // 2 bytes per short
		ibb.order(ByteOrder.nativeOrder());
		indexBuffer = ibb.asShortBuffer();
		indexBuffer.put(indices);
		indexBuffer.position(0);
		
		setTexCoords(texcoords);
	}

	@Override
	/** draw function to display the quad **/
	public void draw(GL10 gl) {
		gl.glPushMatrix();
		gl.glFrontFace(GL10.GL_CCW);
		gl.glEnable(GL10.GL_CULL_FACE);
		gl.glCullFace(GL10.GL_BACK);

		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
		gl.glEnable(GL10.GL_TEXTURE_2D);
        gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
        gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, texcoordBuffer);
        gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId);
        
        
		gl.glTranslatef(px + Constants.limitRight -10, py + Constants.limitDown  - 30, 0);
		gl.glRotatef(rx, 1, 0, 0);
		gl.glRotatef(ry, 0, 1, 0);
		gl.glScalef(1, 1, 1);
		
		
		gl.glDrawElements(GL10.GL_TRIANGLES, indices.length, GL10.GL_UNSIGNED_SHORT, indexBuffer);

		gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
		gl.glDisable(GL10.GL_CULL_FACE);
		gl.glPopMatrix();
	}
	
}
